package com.github.gin.sns.controller;

import com.github.gin.sns.config.WechatProperties;
import com.github.gin.sns.service.MessageDispatcherManager;
import com.github.gin.sns.util.SignatureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by GinPonson on 12/29/2016.
 */
@RestController
@EnableConfigurationProperties(WechatProperties.class)
public class AccessController {

    Logger logger = LoggerFactory.getLogger(AccessController.class);

    @Autowired
    private WechatProperties wechatProperties;

    @RequestMapping(value = "/access", method = {RequestMethod.GET})
    public String access(String signature,String timestamp,String nonce,String echostr) throws Exception {
        if(logger.isDebugEnabled()){
            logger.debug("signature:{},timestamp:{},nonce:{},echostr:{}",signature, timestamp, nonce, echostr);
        }

        if (SignatureUtil.checkSignature(wechatProperties.getToken(),signature, timestamp, nonce)){
            return echostr;
        } else {
            return "error";
        }
    }

    @RequestMapping(value = "/access", method = {RequestMethod.POST})
    public String process(HttpServletRequest req) throws Exception {
        return MessageDispatcherManager.doDispatcher(req.getInputStream());
    }

}
